package com.jeehentor.ai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeehentor.ai.entity.AiPlatformConfig;
import com.jeehentor.ai.service.AiPlatformConfigService;
import com.jeehentor.common.vo.Result;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/ai/config")
@RequiredArgsConstructor
public class AiPlatformConfigController {

    private final AiPlatformConfigService configService;

    /**
     * 分页查询配置
     */
    @GetMapping("/page")
    public Result<?> page(@RequestParam(defaultValue = "1") int page,
                          @RequestParam(defaultValue = "10") int size,
                          @RequestParam(required = false) String platform,
                          @RequestParam(required = false) String name) {
        LambdaQueryWrapper<AiPlatformConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(platform), AiPlatformConfig::getPlatform, platform);
        wrapper.like(StringUtils.isNotBlank(name), AiPlatformConfig::getName, name);
        wrapper.orderByAsc(AiPlatformConfig::getSort).orderByDesc(AiPlatformConfig::getUpdatedAt);
        return Result.ok(configService.page(new Page<>(page, size), wrapper));
    }

    /**
     * 新增配置
     */
    @PostMapping("/save")
    public Result<Void> save(@RequestBody AiPlatformConfig config) {
        configService.save(config);
        return Result.OK();
    }

    /**
     * 修改配置
     */
    @PutMapping("/update")
    public Result<Void> update(@RequestBody AiPlatformConfig config) {
        configService.updateById(config);
        return Result.OK();
    }

    /**
     * 启用某配置（同平台仅一个启用）
     */
    @PutMapping("/activate")
    public Result<Void> activate(@RequestParam Long id) {
        AiPlatformConfig current = configService.getById(id);
        if (current == null) return Result.error("配置不存在");
        configService.lambdaUpdate()
                .eq(AiPlatformConfig::getPlatform, current.getPlatform())
                .set(AiPlatformConfig::getIsActive, 0).update();
        configService.lambdaUpdate()
                .eq(AiPlatformConfig::getId, id)
                .set(AiPlatformConfig::getIsActive, 1).update();
        return Result.OK();
    }

    /**
     * 删除配置
     */
    @DeleteMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        configService.removeById(id);
        return Result.OK();
    }

    /**
     * 查询所有平台列表
     */
    @GetMapping("/platforms")
    public Result<List<String>> platforms() {
        return Result.ok(configService.list()
                .stream().map(AiPlatformConfig::getPlatform).distinct().toList());
    }
}
